package com.ctshk.rpc.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.system.dto.LoginLogDTO;
import com.ctshk.rpc.system.entity.LoginLog;
import com.ctshk.rpc.system.entity.SysDepartment;
import com.ctshk.rpc.system.entity.SysUser;
import com.ctshk.rpc.system.mapper.LoginLogMapper;
import com.ctshk.rpc.system.mapper.SysDepartmentMapper;
import com.ctshk.rpc.system.mapper.SysUserMapper;
import com.ctshk.rpc.system.req.LoginLogReq;
import com.ctshk.rpc.system.service.ILoginLogService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;

/**
 * <p>
 * 操作日志表 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-03-26
 */
@DubboService
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements ILoginLogService {

    @Autowired
    private LoginLogMapper loginLogMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysDepartmentMapper sysDepartmentMapper;

    @Override
    public PageResponse<LoginLogDTO> list(LoginLogReq req) {
        List<Long> originUserIdList = new ArrayList<>();
        if (StringUtils.isNotBlank(req.getUserName())) {
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(StringUtils.isNotBlank(req.getUserName()), "concat( cn_surname, '', cn_name )", req.getUserName());
            // 根据登录账户名查询
            List<SysUser> originSysUserList = userMapper.selectList(queryWrapper);
            originUserIdList = originSysUserList.stream().map(SysUser::getId).distinct().collect(Collectors.toList());
        }
        Page<LoginLog> loginLogPage = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper<LoginLog> queryWrapper = new QueryWrapper<>();
        if (null != req.getEndDate()) {
            req.setEndDate(req.getEndDate().plusDays(1));
        }
        queryWrapper.lambda().eq(StringUtils.isNotBlank(req.getType()), LoginLog::getType, req.getType())
                .in(!originUserIdList.isEmpty(), LoginLog::getUserId, originUserIdList)
                .between((null != req.getStartDate() && null != req.getEndDate()), LoginLog::getGmtCreate, req.getStartDate(), req.getEndDate())
                .select(LoginLog.class, i -> !"gmt_modified".equals(i.getColumn()))
                .orderByDesc(LoginLog::getGmtCreate);
        Page<LoginLog> iPage = loginLogMapper.selectPage(loginLogPage, queryWrapper);
        List<LoginLog> records = iPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageResponse<>(new ArrayList<>(), iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
        }
        List<LoginLogDTO> loginLogDTOList = EntityUtil.copyList(records, LoginLogDTO.class);
        Map<Long, List<LoginLogDTO>> logMap = loginLogDTOList.stream().collect(Collectors.groupingBy(LoginLogDTO::getUserId));

        // 账户信息
        List<Long> userIdList = records.stream().map(LoginLog::getUserId).distinct().collect(Collectors.toList());
        List<SysUser> userList = userMapper.selectBatchIds(userIdList);
        userList.forEach(sysUser -> {
            List<LoginLogDTO> loginLogDTOs = logMap.get(sysUser.getId());
            loginLogDTOs.forEach(loginLogDTO -> {
                loginLogDTO.setUserName(StrUtil.concat(true, sysUser.getCnSurname(), sysUser.getCnName()));

                // 获取账号上级部门
                if (sysUser.getDeptId() != null) {
                    List<SysDepartment> sysDepartments = sysDepartmentMapper.selectParents(sysUser.getDeptId());
                    StringBuilder dept = new StringBuilder();
                    if (CollUtil.isNotEmpty(sysDepartments)) {
                        int i = 0;
                        for (SysDepartment sysDepartment : sysDepartments) {
                            if (i == 2) {
                                // 只获取两级部门
                                break;
                            }
//                            dept.append("/");
                            if (i!=0) {
                            	dept.append("/");
							}
                            dept.append(sysDepartment.getTitle());
                            i++;
                        }
                    }
                    loginLogDTO.setDeptName(String.valueOf(dept));
                }
            });
        });
        return new PageResponse<>(loginLogDTOList, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }
}
